﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Text.RegularExpressions;

namespace Community.SharePoint.FAST.PowerShell
{
    public class FASTProcesses
    {
        private static readonly Regex Searchregex = new Regex(@"searchrc-\d\.xml",
                                                               RegexOptions.IgnoreCase | RegexOptions.Compiled);

        public static List<string> CheckRunningProcesses()
        {
            List<string> processRunning = new List<string>();
            foreach (Process p in Process.GetProcessesByName("fastsearchexec"))
            {
                try
                {
                    using (
                        ManagementObjectSearcher searcher =
                            new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + p.Id))
                    {
                        foreach (string commandLineArgs in
                            from ManagementObject @object in searcher.Get() select @object["CommandLine"] as string)
                        {
                            if (!string.IsNullOrEmpty(commandLineArgs) &&
                                commandLineArgs.ToLower().Contains("configserver.exe"))
                                processRunning.Add("configserver");
                            else if (!string.IsNullOrEmpty(commandLineArgs) &&
                                commandLineArgs.ToLower().Contains("indexer.exe"))
                                processRunning.Add("indexer");
                            else if (!string.IsNullOrEmpty(commandLineArgs) &&
                                commandLineArgs.ToLower().Contains("fsearchctrl.exe"))
                            {
                                Match match = Searchregex.Match(commandLineArgs);
                                if (match.Success)
                                {
                                    processRunning.Add(match.Value.Replace(".xml", "").Replace("rc-", "-"));
                                }
                            }
                        }
                    }
                }
                catch (Win32Exception ex)
                {
                    if ((uint) ex.ErrorCode != 0x80004005)
                    {
                        throw;
                    }
                }
            }
            return processRunning;
        }
    }
}